#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Evaluate distance/angle experiment data
#
# Author: Markus Fuchs
#

import pickle
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import matplotlib, pylab
import matplotlib.image as mpimg
import numpy as np
import math
import sys

# testdata filename format: name _ #samples/angle _ max_angle _ rows _ cols _ receiver_pos.dat
# e.g. name_50_180.dat

# testdata format
# [ { angle#:"#received packets" } ]

def sample_data(count, angles):
    """ generate sample data where count is the number of measuring points """
    data = []
    for i in range(0, count):
        d = {}
        for a in angles:
            d[a] = np.random.rand()*50
        data.append(d)
    return { "data": data, "num_points":count, "num_angles":len(angles), "samples_p_angle":50, "max_angle":360 }

def polar_chart(fig, teststruct, position, max_angle=180, axlabels=True, theta_offset=np.pi):
    """ print polar (KUCHEN) chart for specific measuring point """
    #ax = fig.add_axes([0.1,0.1,0.8,0.8], polar=True)
    ax = fig.gca()
    ax.set_theta_direction(-1) # clockwise angles
    ax.set_theta_offset(theta_offset)
    ax.set_ylim((0,100))
    if not axlabels:
        ax.set_yticklabels([])
        #ax.set_xticks([])
    testcase = teststruct["data"][position]
    if(max_angle == 360):
        width = np.pi/(float(len(testcase.keys()))/2.0)   # for 360°
    else:
        width = np.pi/(float(len(testcase.keys())))         # for 180°
    angles = map(lambda x: width*x, testcase.keys())
    values = [ float(v)/float(teststruct["samples_p_angle"])*100.0 for v in testcase.values() ]
    # colormap
    cmap = matplotlib.colors.LinearSegmentedColormap("colormap",pylab.cm.datad["RdYlGn"], N=100)
    colors = cmap([ int(math.ceil(v)) for v in values ])
    bars = ax.bar(angles, values, width=width, bottom=0.0, color=colors)


def multiple_polar(teststruct, rows, columns, receiver_pos=0):
    data = teststruct["data"]
    fig = plt.figure(1)
    plt.subplots_adjust(wspace=0.25, hspace=0.3)
    tc = 0
    pos = 1
    while tc < len(data):
    # todo if receiver_middle and pos = #per_row/2
        if receiver_pos != 0 and receiver_pos == pos:
            plt.subplot(rows, columns, pos)
            ax = plt.gca()
            ax.set_xticks([])
            ax.set_yticks([])
            img=mpimg.imread('receiver.png')
            plt.imshow(img)
        else:
            plt.subplot(rows, columns, pos, polar=True)
            polar_chart(plt.gcf(), teststruct, tc, max_angle=teststruct["max_angle"], axlabels=False)
            tc += 1
        pos += 1


def linechart_for_angle(fig, teststruct, angle):
    """ draw a line chart for received packets for a specific angle """
    data = teststruct["data"]
    ax = fig.add_subplot(111)
    x_data = range(0, len(data))
    y_data = [k[angle] for k in data]
    # calc percentage
    y_data = map(lambda x: float(x)/teststruct["num_samples_p_angle"]*100, y_data)
    ax.plot(x_data, y_data, "ro")

if len(sys.argv) == 1:
    print "  Usage: " + sys.argv[0] + "testdata"
    t = sample_data(5, [0, 45, 90, 135, 180, 225, 270, 315])
    print "Here is some sample"
    print t
    multiple_polar(t, 2, 3, receiver_pos=2)
    plt.show()	
else:
    filename = sys.argv[1]
    testdata = pickle.load(open(filename, "rb"))
    print testdata
    num_samples_p_angle = int(filename.split("_")[1])
    max_angle = int(filename.split("_")[2])
    rows = int(filename.split("_")[3])
    cols = int(filename.split("_")[4])
    recv_pos = int(filename.split("_")[5])
    # one simple "object" for our functions to process
    test_structure = { "data":testdata, "samples_p_angle":num_samples_p_angle, "max_angle":max_angle }
    if(len(testdata) == 1):
        plt.subplot(1,1,1,polar=True)
        polar_chart(plt.gcf(), test_structure, 0, max_angle=max_angle)
    else:
        multiple_polar(test_structure, rows, cols, receiver_pos = recv_pos)
    plt.show()	